import window from '@ohos.window';
import display from '@ohos.display';
import common from '@ohos.app.ability.common';
import UIAbility from '@ohos.app.ability.UIAbility';
import 'loadingLib/src/main/ets/pages/LoadingPage.ets';

/**
 * 通过创建子窗口来显示Loading弹窗
 */
export class LoadingUtils {
  private static EVENT_CREATE_SUB_WINDOW = 'createSubWindow'
  private static EVENT_CLOSE_SUB_WINDOW = 'closeSubWindow'
  static LOADING_MESSAGE = 'loading_message'

  /**
   * 发送创建loading子窗口的事件，显示loading
   * @param context context
   */
  static showLoading(context: common.UIAbilityContext, message: string = '请稍候') {
    AppStorage.setOrCreate(LoadingUtils.LOADING_MESSAGE, message)
    context?.eventHub.emit(LoadingUtils.EVENT_CREATE_SUB_WINDOW)
  }

  /**
   * 发送关闭loading子窗口的事件，隐藏loading
   * @param context context
   */
  static hideLoading(context: common.UIAbilityContext) {
    context?.eventHub.emit(LoadingUtils.EVENT_CLOSE_SUB_WINDOW)
  }

  /**
   * 订阅创建和关闭loading子窗口的事件
   * @param ability ability
   * @param stage stage
   */
  static subscribeLoadingEvent(ability: UIAbility, stage: window.WindowStage) {
    if (ability) {
      ability.context.eventHub.on(LoadingUtils.EVENT_CREATE_SUB_WINDOW, () => LoadingUtils.showSubWindow(stage))
      ability.context.eventHub.on(LoadingUtils.EVENT_CLOSE_SUB_WINDOW, () => LoadingUtils.closeSubWindow(stage))
    }
  }

  /**
   * 取消订阅创建和关闭loading子窗口的事件
   * @param ability ability
   */
  static unsubscribeLoadingEvent(ability: UIAbility) {
    if (ability) {
      ability.context.eventHub.off(LoadingUtils.EVENT_CREATE_SUB_WINDOW)
      ability.context.eventHub.off(LoadingUtils.EVENT_CLOSE_SUB_WINDOW)
    }
  }

  /**
   * 显示loading子窗口
   * @param stage stage
   */
  static async showSubWindow(stage: window.WindowStage) {
    stage?.createSubWindow('sub_window').then(async win => {
      // 设置子窗口显示的页面
      await win.loadContentByName('LoadingPage')
      let d = display.getDefaultDisplaySync()
      await win.setWindowSystemBarEnable([])
      await win.setWindowLayoutFullScreen(true)
      await win.resize(d.width, d.height)
      // 设置半透明效果
      win.setWindowBackgroundColor('#88000000')
      win.showWindow()
    })
  }

  /**
   * 关闭loading子窗口
   * @param stage stage
   */
  static closeSubWindow(stage: window.WindowStage) {
    stage?.getSubWindow().then(win => {
      if (win.length > 0) {
        win[0].destroyWindow()
      }
    })
  }
}
